import { routerRedux } from 'dva/router';
import { message } from 'antd';
import { reloadAuthorized } from '../utils/Authorized';

import { loginToLoki, logout, fetchCode } from '../services/api';
import { tokensToFunction } from 'path-to-regexp';
export default {
  namespace: 'login',

  state: {
    status: undefined,
    submitting: false,
    codeData: {},
    menuForCurrentUser: [],
    loginResult: {
      result: {},
    },
  },

  effects: {
    *fetchCode({ payload, callback }, { call, put }) {
      const response = yield call(fetchCode, payload);

      yield put({
        type: 'query',
        payload: {
          codeData: response.data,
        },
      });
      if (callback) callback();
    },

    *accountSubmit({ payload }, { call, put }) {
      // console.log("accountSubmit-payload", payload)
      yield put({
        type: 'changeSubmitting',
        payload: true,
      });
      const response = yield call(loginToLoki, payload);
      console.log("response-response11111", response)
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });

      yield put({
        type: 'changeSubmitting',
        payload: false,
      });
      if (response.result.code == 200) {
        sessionStorage.setItem('token', response.data.token);
        sessionStorage.setItem('name', response.data.name);
        sessionStorage.setItem('userName', response.data.userName);
        sessionStorage.setItem('userId', response.data.userId);
        // sessionStorage.setItem("secretKey", response.data.secretKey)
        sessionStorage.setItem('merchantId', response.data.merchantId);
        sessionStorage.setItem('loginSuccessful', true);
        
        yield put(routerRedux.push('/home/home-page'));
      } else {
        message.error(response.result.message);
      }
      // if(callback)callback();
    },

    *logout({ payload }, { call, put }) {
      const response = yield call(logout, payload);
      yield put(routerRedux.push('/user/login'));
    },
  },

  reducers: {
    query(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },

    changeLoginStatus(state, { payload }) {
      return {
        ...state,
        status: payload.status,
        type: payload.type,
        loginResult: payload,
      };
    },
    changeSubmitting(state, { payload }) {
      return {
        ...state,
        submitting: payload,
      };
    },
  },
};
